let COS = require('../../script/lib/cos-wx-sdk-v5.js');
let config = require("../../script/data/config.js");
var requestCallback = (callback)=>{
  return function (err, data) {
    console.log(err || data);
    if (err && err.error) {
      wx.showModal({
        title: '返回错误[COS]',
        content: '请求失败：' + (err.error.Message || err.error) + '；状态码：' + err.statusCode,
        showCancel: false
      });
    } else if (err) {
      wx.showModal({
        title: '请求出错[COS]',
        content: '请求出错：' + err + '；状态码：' + err.statusCode,
        showCancel: false
      });
    } else {
      callback(data);
    }
  };
}

function COSManager (Context){
  this.Context = Context;
  let getAuthorization = (options, callback) => {
    let getTokenSuccess = (res) => {
      callback({
        TmpSecretId: res.tempKeys.credentials.tmpSecretId,
        TmpSecretKey: res.tempKeys.credentials.tmpSecretKey,
        XCosSecurityToken: res.tempKeys.credentials.sessionToken,
        ExpiredTime: res.tempKeys.expiredTime,
      });
    };
    Context._request("cos").getToken({}, {success: getTokenSuccess});
  }, cos = new COS({ getAuthorization, ForcePathStyle: true });
  this.cos = cos;
};
module.exports.COSManager = COSManager;

/**
 * postObject 通过post传送对象进cos
 */
function postObject(key, filePath){
  let then = ()=>{};
  this.cos.postObject({
    Bucket: config.COS.Bucket,Region: config.COS.Region,Key: key,FilePath: filePath,
  }, requestCallback((info) => { then((info)); }));
  return { then: (callback) => {then = callback;}}
}
COSManager.prototype.postObject = postObject;
/**
 * putObject 通过put传送body内容进cos
 */
function putObject(key, body) {
  let then = () => { };
  this.cos.putObject({
    Bucket: config.COS.Bucket, Region: config.COS.Region, Key: key, Body: body,
  }, requestCallback((info) => { then((info)); }));
  return { then: (callback) => { then = callback; } }
}
COSManager.prototype.putObject = putObject;

